<template xmlns:el-col="http://www.w3.org/1999/html">
  <div>
    <div style="background-color: #333333">
      <el-row>
        <el-col :span="3">
          <el-input
            v-model="searchInput"
            placeholder="选择年月日"
            @input="watchsearch"
            disabled="true"
            size="mini"

          ></el-input>
        </el-col>

        <el-col :span="5">
          <el-date-picker
            size="mini"
            type="date"
            placeholder="请选择培训起始时间和日期"
            value-format="yyyy-MM-dd"
            @input="watchs"
            v-model="dates">
          </el-date-picker>
        </el-col>
        <el-col :span="3">
          <el-button @click="selectAttendByCheckdate">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="openinsertdialog">创建考勤</el-button>
        </el-col>
        <!--      <el-col :span="2">-->
        <!--        <el-button @click="newTrain">上班打卡</el-button>-->
        <!--      </el-col>-->
        <!--      <el-col :span="2">-->
        <!--        <el-button @click="newTrain">下班打卡</el-button>-->
        <!--      </el-col>-->
        <el-col :span="2">
          <el-button @click="deleteAttendance">删除考勤</el-button>
        </el-col>
        <el-col :span="2">

          <el-button @click="exportExcel">导出当前考勤表</el-button>

        </el-col>
        <el-col :span="4">
          <el-button @click="returnlogin">返回首页</el-button>
        </el-col>
      </el-row>
      <el-row>
        <!--      <el-col :span="3">-->
        <!--        <span style="color: #F5F7FA">输入查询的userId</span>-->
        <!--      </el-col>-->
        <el-col :span="3">
          <el-input placeholder="输入userId" v-model="selectuserId"></el-input>
        </el-col>
        <!--      <el-col :span="5">-->
        <!--        <el-date-picker-->
        <!--          size="mini"-->
        <!--          type="date"-->
        <!--          placeholder="请选择日期"-->
        <!--          value-format="yyyy-MM-dd"-->
        <!--          @input="watchs"-->
        <!--          >-->
        <!--        </el-date-picker>-->
        <!--      </el-col>-->
        <el-col :span="3">
          <el-button @click="reloadWorkAttendanceDayByuserId">查询本id今日考勤</el-button>
        </el-col>
        <el-col :span="3">
          <el-button @click="reloadWorkAttendanceMonthByuserId">查询本id本月考勤</el-button>
        </el-col>
        <el-col :span="3">
          <el-button @click="reloadAllAttendanceDescAll">查看所有考勤信息</el-button>
        </el-col>
        <el-col :span="3">
          <el-button @click="reloadAllAttendanceDesc">查看本月所有考勤信息</el-button>
        </el-col>
      </el-row>

      <span>{{dates}}</span>
    </div>
    <div>
      <el-table
        :data="workAttendance"
        :row-style="{height: '0'}"
        :cell-style="{padding: '0'}"
        style="width: 100%"
        @row-click="getDetails"
        id="out-table"
        @selection-change="handleAttendanceChange"
      >
        <!--        <el-table-column label width="35">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-radio :label="scope.row.name" v-model="radioId">&nbsp;</el-radio>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column type="selection" width="55" align="center" fixed/>
        <el-table-column align="center" prop="attendance" label="考勤序列" width="80" ></el-table-column>
        <el-table-column align="center" prop="userId" label="员工Id" width="100" fixed></el-table-column>
        <el-table-column align="center" prop="username" label="姓名" width="75"></el-table-column>
        <el-table-column align="center" prop="checkdate" label="考勤日期" width="100"></el-table-column>
        <el-table-column align="center" prop="checkstarttime" label="考勤开始时间" width="100"></el-table-column>
        <el-table-column align="center" prop="checkendtime" label="考勤结束时间" width="100"></el-table-column>0
        <el-table-column align="center" prop="checkstartdate" label="考勤详细开始时间" width="100"></el-table-column>
        <el-table-column align="center" prop="checkenddate" label="考勤详细结束时间" width="100"></el-table-column>
        <el-table-column align="center" prop="attendcheckdate" label="考勤日期" width="100"></el-table-column>
        <el-table-column align="center" prop="checktype" label="打卡状态" width="160" >

          <template slot-scope="scope">
            <span v-if="scope.row.checktype == 6" class="el-icon-warning" style="color:purple;"></span>
            <span v-if="scope.row.checktype == 5" class="el-icon-warning" style="color:yellow;"></span>
            <span v-if="scope.row.checktype == 4" class="el-icon-error" style="color:red;"></span>
            <span v-if="scope.row.checktype == 3" class="el-icon-warning" style="color:yellow;"></span>
            <span v-if="scope.row.checktype == 2" class="el-icon-info" style="color:blue;"></span>
            <span v-if="scope.row.checktype == 1" class="el-icon-success" style="color:rgb(103, 194, 58);"></span>
            <span v-if="scope.row.checktype == 0" class="el-icon-question" style="color: gray;"></span>
            {{ changeChecktype(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="attendtype" label="打卡类型（上下班）" width="100"></el-table-column>
        <el-table-column align="center" prop="workhour" label="加班时长" width="100"></el-table-column>
        <el-table-column fixed="right" width="200" label="操作">
          <template slot-scope="scope">
            <el-button v-show="scope.row.checktype==0&&scope.row.attendtype=='上班'" @click="startworkAttendance(scope.row)" style="padding: 3px" size="mini" type="success">上班签到</el-button>
            <el-button v-show="scope.row.checktype==0&&scope.row.attendtype=='下班'" @click="startworkAttendance(scope.row)" style="padding: 3px" size="mini" type="success">下班签到</el-button>
            <el-button v-show="scope.row.checktype==0" @click="absentAttendance(scope.row)" style="padding: 3px;color: blueviolet" size="mini" type="success">请假</el-button>
            <el-button v-show="scope.row.checktype==4&&checkInTimeBound(scope.row.checkenddate)" @click="resetAttendance(scope.row)" style="padding: 3px;color: white" size="mini" type="warning">补签</el-button>
            <el-button v-show="scope.row.checktype==1&&scope.row.attendtype=='下班'" @click="workhardAttendance(scope.row)" style="padding: 3px;color: white" size="mini" type="primary">加班</el-button>


            <!--            <el-button @click="deleteEmp(scope.row)" style="padding: 3px" size="mini" type="danger">删除-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="新 建 考 勤"
        :visible.sync="insertdialog"
        width="80%"
        :before-close="handleCloseInsert">
        <el-form ref="form" label-width="100px" v-model="workAttendance" :rules="rule">
          <el-row>
            <el-col :span="8">

              <el-form-item label="选择考勤日期">
                <el-date-picker
                  size="mini"
                  type="date"
                  placeholder="请选择考勤日期"
                  value-format="yyyy-MM-dd"
                  v-model="selectcheckdate">
                </el-date-picker></el-form-item>
            </el-col>
            <el-col :span="8">

              <el-form-item label="起始具体时间">
                <el-date-picker
                  size="mini"
                  type="datetime"
                  placeholder="请选择起始时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="selectstartdate">
                </el-date-picker></el-form-item>
            </el-col>
            <el-col :span="8">

              <el-form-item label="起始结束时间">
                <el-date-picker
                  size="mini"
                  type="datetime"
                  placeholder="请选择结束时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="selectenddate">
                </el-date-picker></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <el-form-item label="选择考勤类别">
                <el-select v-model="selectattendtype" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button @click="createAttendance">
                  创建考勤
                </el-button>
              </el-form-item>

            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button @click="handleCloseInsert">
                  取消
                </el-button>
              </el-form-item>

            </el-col>

          </el-row>
        </el-form>
        <!--      <span>{{selectcheckdate}}</span>-->
        <!--      <span>{{selectstartdate}}</span>-->
        <!--      <span>{{selectenddate}}</span>-->
        <!--      <span>{{selectattendtype}}</span>-->
        <el-table
          :data="IdAndName"
          :row-style="{height: '0'}"
          :cell-style="{padding: '0'}"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column align="center" prop="userId" label="员工Id" width="150" fixed></el-table-column>
          <el-table-column align="center" prop="username" label="姓名" width="150"></el-table-column>
        </el-table>

      </el-dialog>
    </div>
  </div>
</template>

<script>
  import XLSX from "xlsx";
  import FileSaver from 'file-saver'

  export default {
    name: "departmentWorkAttendance",
    data(){
      return{
        dates:this.getNowFormatDateDDDD(),
        workAttendance:[],
        workAttendances:{
          attendance:"",
          userId:"",
          userName:"",
          checkdate:"",
          checkstarttime:"",
          checkendtime:"",
          checkstartdate:"",
          checkenddate:"",
          attendcheckdate:"",
          checktype:"",
          createdate:"",
          attendtype:"",
          workhour:"",
        },
        insertdialog:false,
        Ids:[],
        Attendances:[],
        Names:[],
        IdAndName:[],
        selectedNum:0,
        selectcheckdate:"",
        selectstartdate:"",
        selectenddate:"",
        selectattendtype:"",
        selectuserIdAndusername:[],
        options:[
          {
            label:"上班",
            value:"上班"
          },
          {
            label:"下班",
            value:"下班"
          }
        ],
        selectuserId:"",

      }
    },
    mounted() {
      this.$store.state.departmentId = window.sessionStorage.getItem("departmentId")
      this.selectAttendByCheckdate()
      this.reloadAllEmpNameAndId();
    },
    methods:{

      //定义导出Excel表格事件
      exportExcel() {
        let xlsxParam = { raw: true }; //转换成excel时，使用原始的格式
        / generate workbook object from table /;
        /* 从表生成工作簿对象 */
        let table =  document.querySelector("#out-table").cloneNode(true)
        // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里删除掉
        table.removeChild(table.querySelector(".el-table__fixed-right"));
        table.removeChild(table.querySelector(".el-table__fixed"));
        let wb = XLSX.utils.table_to_book(
          table ,  //elementui 表格的id
          xlsxParam
        );

        /* 获取二进制字符串作为输出 */
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            //Blob 对象表示一个不可变、原始数据的类文件对象。
            //Blob 表示的不一定是JavaScript原生格式的数据。
            //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
            //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
            new Blob([wbout], { type: "application/octet-stream" }),
            //设置导出文件名称
            JSON.stringify(this.dates).replace(/\"/g, "")+"考勤表.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },

      reloadWorkAttendanceDayByuserId()
      {
        this.$axios.post("/Work_attendance/selectDayAttendanceByuserIdAndDepId",{
          userId:this.selectuserId,
          checkdate:this.dates,
          departmentId:this.$store.state.departmentId
        }).then((res)=>{
          this.workAttendance=[],
            this.workAttendance = res.data
          return this.$message.success("查询成功")
        })
      },
      reloadWorkAttendanceMonthByuserId()
      {
        this.$axios.post("/Work_attendance/selectMonthAttendanceByuserId",{
          userId:this.selectuserId,
          checkdate:this.dates
        }).then((res)=>{
          this.workAttendance=[],
            this.workAttendance = res.data
          return this.$message.success("查询成功")
        })
      },
      returnlogin(){
        this.$store.commit("setviewPage",1);
        this.$router.push({path: '/home'})
      },
      watchs()
      {
        if(this.dates == null)
        {
          this.reloadAllAttendanceDesc();
        }
        else {
          this.selectAttendByCheckdate()
        }

      },
      selectAttendByCheckdate()
      {
        if(this.dates == null)
        {
          this.reloadAllAttendanceDesc();

        }
        else {
          this.$axios.post("/Work_attendance/selectAllWorkAttendanceByDepartmentId",{
              departmentId:this.$store.state.departmentId,
              checkdate:this.dates
          }).then((res)=>{
            this.workAttendance =[],
              this.workAttendance = res.data
          })



        //  alert(JSON.stringify(this.dates))
          this.$axios.post("/Work_attendance/selectAttendByCheckdateAndDepId",{
            departmentId:this.$store.state.departmentId,
            checkdate:this.dates
          }).then((res)=>{
            this.workAttendance =[],
              this.workAttendance = res.data
            return this.$message.success("获取成功")
          })
        }

      },
      openinsertdialog()
      {
        this.$axios.post("/Work_attendance/selectAllEmpUserIdAndUsername",{

        }).then((res)=>{

        })
        this.insertdialog = true
      },
      reloadAllAttendanceDesc(){

        this.$axios.post("/Work_attendance/selectAllWorkAttendanceByDepartmentId",{
          departmentId:this.$store.state.departmentId
        }).then((res)=>{
          this.workAttendance =[],
            this.workAttendance = res.data
        })


      },
      reloadAllAttendanceDescAll(){
        this.$axios.post("/Work_attendance/selectAllWorkAttendanceByDepartmentIdThisMonth",{
            departmentId:this.$store.state.departmentId,
            checkdate:this.dates
        }).then((res)=>{
          this.workAttendance = []
          // alert(JSON.stringify(res.data))
          this.workAttendance = res.data
          return this.$message.success("已加载全部")
        })
      },
      reloadAllEmpNameAndId()
      {
        this.$axios.post("/Work_attendance/selectAllDepEmpUserIdAndUsername",{
          departmentId:this.$store.state.departmentId
        }).then((res)=>{
          this.IdAndName = []
          this.IdAndName = res.data
          // alert(JSON.stringify(this.IdAndName))
        })
      },
      changeChecktype(row)
      {
        // alert(JSON.stringify(row.checktype))
        if(row.checktype=='1')
        {
          return "正常"
        }
        else if(row.checktype=='0'){
          return "未签到"
        }
        else if(row.checktype=='2'){
          return "请假"
        }
        else if(row.checktype=='3'){
          return "迟到"
        }
        else if(row.checktype=='4')
        {
          return "缺勤"
        }
        else if(row.checktype=='5')
        {
          return "早退"
        }
        else if(row.checktype =='6')
        {
          return "加班"
        }
      },
      handleCloseInsert(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.selectcheckdate="",
              this.selectstartdate="",
              this.selectenddate="",
              this.selectattendtype="",
              this.insertdialog = false
            done();
          })
          .catch(_ => {

          }).finally(
          ()=>{
            this.reloadAllEmpNameAndId();
            this.reloadAllAttendanceDesc()
          })
      },
      handleSelectionChange(selection) {
        this.selectuserIdAndusername =selection.map(item=>(item))

        // alert(JSON.stringify(this.selectuserIdAndusername))
        this.Ids = selection.map(item => (item.userId))
        this.Names = selection.map(item => (item.username))
        this.selectedNum = selection.length
      },
      handleAttendanceChange(selection) {
        this.selectuserIdAndusername =selection.map(item=>(item))


        this.Attendances = selection.map(item=>(item.attendance))
        alert(JSON.stringify(this.Attendances))
        this.selectedNum = selection.length
      },

      //获取当前时间
      getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
          + " " + date.getHours() + seperator2 + date.getMinutes()
          + seperator2 + date.getSeconds();
        return currentdate;
      },
      createAttendance()
      {
        this.$axios.post("/Work_attendance/createNewAttendance" ,{
          Ids:this.Ids,
          Names:this.Names,
          checkdate:this.selectcheckdate,
          checkstartdate:this.selectstartdate,
          checkenddate:this.selectenddate,
          createdate:this.getNowFormatDate(),
          attendtype:this.selectattendtype,
          headers: {
            'Content-type': 'application/json;charset=UTF-8'
          },
        }).then((res)=>{
          this.insertdialog = false
          this.reloadAllAttendanceDesc()
          this.reloadAllEmpNameAndId()
          return this.$message.success(res.data.msg)
        })
      },
      startworkAttendance(data)
      {
        // alert(JSON.stringify(data).replace(/\"/g, ""))

        this.$axios.post("/Work_attendance/UpdateAttendcheckdate",{
          attendance:data.attendance,
          userId:data.userId,
          username:data.username,
          checkdate:data.checkdate,
          checkstarttime:data.checkstarttime,
          checkendtime:data.checkendtime,
          checkstartdate:data.checkstartdate,
          checkenddate:data.checkenddate,
          attendcheckdate:data.attendcheckdate,
          checktype:data.checktype,
          createdate:data.createdate,
          attendtype:data.attendtype,
          workhour:data.workhour,
        }).then((res)=>{
          return this.$message.success(res.data.msg)
        }).catch(()=>{
          return this.$message.error("签到失败")
        }).finally(()=>{
          this.reloadAllAttendanceDesc()
        })


      },
      absentAttendance(data)
      {
        this.$axios.post("/Work_attendance/UpdateAttendcheckdate",{
          attendance:data.attendance,
          userId:data.userId,
          username:data.username,
          checkdate:data.checkdate,
          checkstarttime:data.checkstarttime,
          checkendtime:data.checkendtime,
          checkstartdate:data.checkstartdate,
          checkenddate:data.checkenddate,
          attendcheckdate:data.attendcheckdate,
          checktype:'2',
          createdate:data.createdate,
          attendtype:data.attendtype,
          workhour:data.workhour,
        }).then((res)=>{
          return this.$message.success(res.data.msg)
        }).catch((res)=>{
          return this.$message.error(res.data.msg)
        }).finally(()=>{
          this.reloadAllAttendanceDesc()
        })
      },
      resetAttendance(data)
      {
        this.$axios.post("/Work_attendance/UpdateAttendcheckdate",{
          attendance:data.attendance,
          userId:data.userId,
          username:data.username,
          checkdate:data.checkdate,
          checkstarttime:data.checkstarttime,
          checkendtime:data.checkendtime,
          checkstartdate:data.checkstartdate,
          checkenddate:data.checkenddate,
          attendcheckdate:data.attendcheckdate,
          checktype:'4',
          createdate:data.createdate,
          attendtype:data.attendtype,
          workhour:data.workhour,
        }).then((res)=>{
          return this.$message.success(res.data.msg)
        }).catch((ress)=>{
          return this.$message.error(ress.data.msg)
        }).finally(()=>{
          this.reloadAllAttendanceDesc()
        })
      },
      workhardAttendance(data)
      {
        this.$axios.post("/Work_attendance/UpdateAttendcheckdate",{
          attendance:data.attendance,
          userId:data.userId,
          username:data.username,
          checkdate:data.checkdate,
          checkstarttime:data.checkstarttime,
          checkendtime:data.checkendtime,
          checkstartdate:data.checkstartdate,
          checkenddate:data.checkenddate,
          attendcheckdate:data.attendcheckdate,
          checktype:data.checktype,
          createdate:data.createdate,
          attendtype:data.attendtype,
          workhour:data.workhour,
        }).then((res)=>{
          return this.$message.success(res.data.msg)
        }).catch((ress)=>{
          return this.$message.error(ress.data.msg)
        }).finally(()=>{
          this.reloadAllAttendanceDesc()
        })
      },
      CancelRunAttendance(data)
      {
        this.$axios.post("/Work_attendance/UpdateAttendcheckdate",{
          attendance:data.attendance,
          userId:data.userId,
          username:data.username,
          checkdate:data.checkdate,
          checkstarttime:data.checkstarttime,
          checkendtime:data.checkendtime,
          checkstartdate:data.checkstartdate,
          checkenddate:data.checkenddate,
          attendcheckdate:data.attendcheckdate,
          checktype:data.checktype,
          createdate:data.createdate,
          attendtype:data.attendtype,
          workhour:data.workhour,
        }).then((res)=>{
          return this.$message.success(res.data.msg)
        }).catch((ress)=>{
          return this.$message.error(ress.data.msg)
        }).finally(()=>{
          this.reloadAllAttendanceDesc()
        })
      },
      checkInTimeBound(endTime)
      {
        // alert(startTime)
        // alert(endTime)
        var nowTime = new Date()
        var beginDate = new Date(endTime)
        var  endDate =new Date(endTime)
        endDate.setMinutes(endDate.getMinutes()+30)
        // alert(beginDate)
        // alert(endDate)
        if(nowTime>=beginDate&&nowTime<=endDate) {
          return true
        }
        else{
          return false
        }
      },

      checkRunBound(startTime,endTime)
      {
        // alert(startTime)
        // alert(endTime)
        var nowTime = new Date()
        var beginDate = new Date(startTime)
        var  endDate =new Date(endTime)
        if(nowTime>=beginDate&&nowTime<=endDate) {
          return true
        }
        else{
          return false
        }
      },
      deleteAttendance()
      {
        this.$axios.post("/Work_attendance/DeleteWorkAttendanceByattendance",{
          attendances:this.Attendances
        }).then((res)=>{
          this.reloadAllEmpNameAndId()
          this.reloadAllAttendanceDesc()
          return this.$message.success(res.data.msg)
        }).catch((res)=>{
          return this.$message.error(res.data.msg)
        })
      },
      getNowFormatDateDDDD() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
      }
    }
  }
</script>

<style  scoped>
  .textarea>>>.el-input__inner{
    font-size: 18px!important;
    color:#330099!important;
  }
  /deep/
  input[disabled],input:disabled,input.disabled{
    -webkit-text-fill-color:#C0C4CC;
    background: #F5F7FA;
    -webkit-opacity:1;
    opacity: 1;
    cursor: not-allowed;
  }

</style>
